﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Base.DAL;
using System.IO;
using Base.Util;
using MPSystem.Util;

namespace Base.BLL
{
    public class FtpService
    {        
        #region 参数配置
        private FtpHelper ftp;
        //是否推送综采数据
        public bool PushZC = true;
        //是否推送顶板离层数据
        public bool PushDBLC = true;
        //是否推送锚杆/索应力数据
        public bool PushMGYL = true;
        //是否推送测区应力数据
        public bool PushCQYL = true;

        //本地保存目录
        public string SaveDir="";
        //是否保存到本地
        public bool SendLocal = true;
        //是否推送到FTP
        public bool SendFTP = true;

        private string lastError;
        /// <summary>
        /// 最近一次出现错误的描述
        /// </summary>
        public string LastError { get { return lastError; } }

        #endregion

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="host">ftp主机名</param>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        public FtpService(string host, string username, string password)
        {
            ftp = new FtpHelper(host, username, password);
        }
        //FTP2
        public FtpService(string host, string username,int port,  string password)
        {
            ftp = new FtpHelper(host, username,port, password);
        }

        public bool Connectable()
        {
            bool rst=ftp.Connectable();
            lastError = ftp.LastError;
            return rst;
        }
        //FTP2
        public bool Connectable(string filesDir)
        {
            bool rst = ftp.Connectable(filesDir);
            lastError = ftp.LastError;
            return rst;
        }
        /// <summary>
        /// 发送当前时刻数据（旧格式）
        /// </summary>
        /// <returns>是否成功发送</returns>
        public bool Send()
        {
            if(!PushZC && !PushDBLC && !PushMGYL && !PushCQYL)
            {
                return true;
            }
            if(!Connectable())
            {
                return false;
            }
            //生成文件
            FileStream fsDev=null;
            FileStream fsData = null;
            try
            {
                fsDev = new FileStream("dev.txt", FileMode.Create);
                StreamWriter swDev = new StreamWriter(fsDev);
                swDev.NewLine = Environment.NewLine;
                fsData = new FileStream("rdata.txt", FileMode.Create);
                StreamWriter swData = new StreamWriter(fsData);
                swData.NewLine = Environment.NewLine;
                //综采参数
                string sql = @"SELECT cq.CQBH,YLFJBH,KM,GZMMC,WZ,DYZJBH,YLSX,YLXX FROM SYSTEMKMB km
                                    INNER JOIN SYSTEMCQB cq on cq.KMBH=km.KMBH
                                    INNER JOIN SYSTEMGZMB gzm on gzm.CQBH=cq.CQBH
                                    INNER JOIN ZCCSB cs on cs.GZMBH=gzm.GZMBH
                                    INNER JOIN ZCYLFJWZB wz on wz.GZMBH=gzm.GZMBH
                                    WHERE cq.ZT=1 AND gzm.ZT=1
                                    ORDER BY gzm.GZMBH,YLFJBH,DYZJBH";
                IEnumerable<_ZC> iniZc = null;
                int count = 0;
                if (PushZC)
                {
                    iniZc = Db.Query<_ZC>(sql);
                    count += iniZc.Count();
                }
                //顶板离层参数
                sql = @"SELECT cq.CQBH,CGQBH,KM,XDMC,CGQWZ,WYBJZ FROM SYSTEMKMB km
                        INNER JOIN SYSTEMCQB cq on cq.KMBH=km.KMBH
                        INNER JOIN SYSTEMXDB xd on xd.CQBH=cq.CQBH
                        INNER JOIN DBLCCSB cs on cs.XDBH=xd.XDBH
                        INNER JOIN DBLCCGQWZB wz on wz.XDBH=xd.XDBH
                        WHERE cq.ZT=1 AND xd.ZT=1
                        ORDER BY xd.XDBH,CGQBH";
                IEnumerable<_DBLC> iniDblc = null;
                if (PushDBLC) 
                {
                    iniDblc=Db.Query<_DBLC>(sql);
                    count += iniDblc.Count();
                }
                //锚杆/索应力参数
                sql = @"SELECT cq.CQBH,CGQBH,KM,XDMC,CGQWZ,MGBJZ,MSBJZ FROM SYSTEMKMB km
                        INNER JOIN SYSTEMCQB cq on cq.KMBH=km.KMBH
                        INNER JOIN SYSTEMXDB xd on xd.CQBH=cq.CQBH
                        INNER JOIN MGYLCSB cs on cs.XDBH=xd.XDBH
                        INNER JOIN MGYLCGQWZB wz on wz.XDBH=xd.XDBH
                        WHERE cq.ZT=1 AND xd.ZT=1
                        ORDER BY xd.XDBH,CGQBH";
                IEnumerable<_MGYL> iniMgyl = null;
                if (PushMGYL) 
                {
                    iniMgyl = Db.Query<_MGYL>(sql);
                    count += iniMgyl.Count();
                }
                //测区应力参数
                sql = @"SELECT cq.CQBH,CGQBH,KM,XDMC,CGQWZ,CQCSYY FROM SYSTEMKMB km
                        INNER JOIN SYSTEMCQB cq on cq.KMBH=km.KMBH
                        INNER JOIN SYSTEMXDB xd on xd.CQBH=cq.CQBH
                        INNER JOIN CQYLCSB cs on cs.XDBH=xd.XDBH
                        INNER JOIN CQYLCGQWZB wz on wz.XDBH=xd.XDBH
                        WHERE cq.ZT=1 AND xd.ZT=1
                        ORDER BY xd.XDBH,CGQBH";
                IEnumerable<_CQYL> iniCqyl = null;
                if (PushCQYL) 
                {
                    iniCqyl = Db.Query<_CQYL>(sql);
                    count += iniCqyl.Count();
                }
                swDev.WriteLine(DateTime.Now.ToString("18,yyyy-MM-dd HH:mm:ss,0,"+count+",0,0,0,,,,,0"));                
                string format = "";
                //写入文件
                if (PushZC)
                {
                    format = "{0:D2}{1:D3}ZP{2},{3}{4}{5}{6}支架P{2}压力,36,Mpa,60,0,,{7:0.0},{8:0.0},";
                    foreach (var d in iniZc)
                    {
                        for (int i = 1; i <= 3; i++)
                        {
                            swDev.WriteLine(String.Format(format, d.CQBH, d.YLFJBH, i, d.KM, d.GZMMC, d.WZ, d.DYZJBH, d.YLSX, d.YLXX));
                        }
                    }                    
                }
                if (PushDBLC)
                {
                    format = "{0:D2}{1:D3}L{2},{3}{4}{5}L{2}相对离层量,37,mm,{5},{6:0.0},0.0,";
                    foreach (var d in iniDblc)
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            char AB = (char)(65 + i);
                            string part = i == 0 ? "300,0" : ",,";
                            swDev.WriteLine(String.Format(format, d.CQBH, d.CGQBH, AB, d.KM, d.XDMC, d.CGQWZ, part, d.WYBJZ));
                        }
                    }
                }
                if (PushMGYL)
                {
                    format = "{0:D2}{1:D3}M,{2}{3}{4}锚杆应力,38,KN,500,0,,{5:0.0},";
                    foreach (var d in iniMgyl)
                    {
                        swDev.WriteLine(String.Format(format, d.CQBH, d.CGQBH, d.KM, d.XDMC, d.CGQWZ, d.MGBJZ));
                    }
                }
                if (PushCQYL)
                {
                    format = "{0:D2}{1:D3}Y,{2}{3}{4}围岩应力,39,Mpa,30,0,,,,";
                    foreach (var d in iniCqyl)
                    {
                        swDev.WriteLine(String.Format(format, d.CQBH, d.CGQBH, d.KM, d.XDMC,d.CGQBH));
                    }
                }
                swDev.Flush();
                swDev.Close();
                swData.Flush();
                swData.Close();
                return true;
            }
            catch (Exception ex)
            {
                lastError = ex.Message;
                LoggerHelper.Error(ex.StackTrace);
                Console.WriteLine(lastError);
            }
            finally
            {
                if (fsDev!=null)
                {
                    fsDev.Close();
                }
                if (fsData != null)
                {
                    fsData.Close();
                }
            }
            return false;
        }
        /// <summary>
        /// 生成当前时刻系统参数配置文件（新格式）
        /// </summary>
        /// <returns>是否成功发送</returns>
        public bool SendIni()
        {
            if ((!SendLocal && !SendFTP)
                ||(!PushZC && !PushDBLC && !PushMGYL && !PushCQYL))
            {
                return true;
            }
            if (SendFTP && !Connectable())
            {
                return false;
            }
            //生成文件
            FileStream fsDev = null;
            string saveFile=DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") +"_config.txt";
            try
            {
                fsDev = new FileStream("dev.txt", FileMode.Create);
                StreamWriter swDev = new StreamWriter(fsDev,Encoding.UTF8);
                swDev.NewLine = Environment.NewLine;
                //获取编码
                string bm = Db.Find<SYSTEMKMB>().TELNUM;
                //测区参数
                string sql = @"SELECT CQBH,CQMC FROM SYSTEMCQB
                                    WHERE ZT=1
                                    ORDER BY CQBH";
                foreach (var cq in Db.Query<_CQ>(sql))
                {
                    swDev.Write(bm+";" +cq.CQMC+";KJ440");
                    //综采参数
                    sql = @"SELECT YLFJBH,GZMMC,WZ,DYZJBH,YLSX,YLXX FROM SYSTEMGZMB gzm
                                INNER JOIN ZCCSB cs on cs.GZMBH=gzm.GZMBH
                                INNER JOIN ZCYLFJWZB wz on wz.GZMBH=gzm.GZMBH
                                WHERE gzm.ZT=1 AND gzm.CQBH="+cq.CQBH+
                                "ORDER BY gzm.GZMBH,YLFJBH,DYZJBH";
                    IEnumerable<_ZC> iniZc = null;
                    int count = 0;
                    if (PushZC)
                    {
                        iniZc = Db.Query<_ZC>(sql);
                        count += iniZc.Count();
                    }
                    //顶板离层参数
                    sql = @"SELECT CGQBH,XDMC,CGQWZ,WYBJZ FROM SYSTEMXDB xd
                            INNER JOIN DBLCCSB cs on cs.XDBH=xd.XDBH
                            INNER JOIN DBLCCGQWZB wz on wz.XDBH=xd.XDBH
                            WHERE xd.ZT=1 AND xd.CQBH="+cq.CQBH+
                            "ORDER BY xd.XDBH,CGQBH";
                    IEnumerable<_DBLC> iniDblc = null;
                    if (PushDBLC)
                    {
                        iniDblc = Db.Query<_DBLC>(sql);
                        count += iniDblc.Count();
                    }
                    //锚杆/索应力参数
                    sql = @"SELECT CGQBH,XDMC,CGQWZ,MGBJZ,MSBJZ FROM SYSTEMXDB xd
                            INNER JOIN MGYLCSB cs on cs.XDBH=xd.XDBH
                            INNER JOIN MGYLCGQWZB wz on wz.XDBH=xd.XDBH
                            WHERE xd.ZT=1 AND xd.CQBH="+cq.CQBH+
                            "ORDER BY xd.XDBH,CGQBH";
                    IEnumerable<_MGYL> iniMgyl = null;
                    if (PushMGYL)
                    {
                        iniMgyl = Db.Query<_MGYL>(sql);
                        count += iniMgyl.Count();
                    }
                    //测区应力参数
                    sql = @"SELECT CGQBH,XDMC,CGQWZ,CQCSYY FROM SYSTEMXDB xd
                            INNER JOIN CQYLCSB cs on cs.XDBH=xd.XDBH
                            INNER JOIN CQYLCGQWZB wz on wz.XDBH=xd.XDBH
                            WHERE xd.ZT=1 AND xd.CQBH="+cq.CQBH+
                            "ORDER BY xd.XDBH,CGQBH";
                    IEnumerable<_CQYL> iniCqyl = null;
                    if (PushCQYL)
                    {
                        iniCqyl = Db.Query<_CQYL>(sql);
                        count += iniCqyl.Count();
                    }
                    
                    string format = "";
                    bool noBefore = true;
                    //写入文件
                    if (PushZC)
                    {
                        format = "{0:D2}{1:D3}ZP{2};2;Z;MPa;支架{3}{4};0;0;0;{5}";
                        for (int i = 0; i < iniZc.Count();i++ )
                        {
                            var d = iniZc.ElementAt(i) ;
                            for (int j = 1; j <= 3; j++)
                            {
                                swDev.WriteLine(noBefore ? "|" : "~");
                                noBefore = false;
                                string line = String.Format(format, cq.CQBH, d.YLFJBH, j, d.DYZJBH, d.WZ, d.GZMMC);
                                swDev.Write(line);
                            }
                        }
                    }
                    if (PushDBLC)
                    {
                        format = "{0:D2}{1:D3}L{2};3;Z;mm;{3};0;0;0;{4}";
                        for (int i = 0; i < iniDblc.Count(); i++)
                        {
                            var d = iniDblc.ElementAt(i);
                            for (int j = 1; j <= 2; j++)
                            {
                                swDev.WriteLine(noBefore ? "|" : "~");
                                noBefore = false;
                                string line = String.Format(format, cq.CQBH, d.CGQBH, j, d.CGQWZ, d.XDMC);
                                swDev.Write(line);
                            }
                        }
                    }
                    if (PushMGYL)
                    {
                        format = "{0:D2}{1:D3}M;5;Z;KN;{2};0;0;0;{3}";
                        for (int i = 0; i < iniMgyl.Count(); i++)
                        {
                            swDev.WriteLine(noBefore ? "|" : "~");
                            noBefore = false;
                            var d = iniMgyl.ElementAt(i);
                            string line=String.Format(format, cq.CQBH, d.CGQBH, d.CGQWZ, d.XDMC);
                            swDev.Write(line);
                        }
                    }
                    if (PushCQYL)
                    {
                        format = "{0:D2}{1:D3}Y;1;Z;KN;;0;0;0;{2}";
                        for (int i = 0; i < iniCqyl.Count(); i++)
                        {
                            swDev.WriteLine(noBefore ? "|" : "~");
                            noBefore = false;
                            var d = iniCqyl.ElementAt(i);
                            string line = String.Format(format, cq.CQBH, d.CGQBH, d.XDMC);
                            swDev.Write(line);
                        }
                    }
                    swDev.WriteLine("||");
                }
                swDev.Flush();
                swDev.Close();
                //保存到本地目录
                bool rst = true;
                if (SendLocal)
                {
                    File.Copy("dev.txt", SaveDir + "\\"+saveFile);
                    rst &= ftp.Upload(new FileInfo("dev.txt"), saveFile);
                }
                if (SendFTP)
                {
                    rst &= ftp.Upload(new FileInfo("dev.txt"), saveFile);
                }
                return rst;
            }
            catch (Exception ex)
            {
                lastError = ex.Message;
                LoggerHelper.Error(ex.StackTrace);
                Console.WriteLine(lastError);
            }
            finally
            {
                if (fsDev != null)
                {
                    fsDev.Close();
                }
            }
            return false;
        }
        /// <summary>
        /// 生成当前时刻数据文件（新格式）
        /// 离当前时刻最近的一次数据
        /// </summary>
        /// <returns>是否成功发送</returns>
        public bool SendData()
        {
            if ((!SendLocal && !SendFTP)
                || (!PushZC && !PushDBLC && !PushMGYL && !PushCQYL))
            {
                return true;
            }
            if (SendFTP && !Connectable())
            {
                return false;
            }
            //生成文件
            FileStream fsData = null;
            string saveFile = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + "_data.txt";
            try
            {
                fsData = new FileStream("data.txt", FileMode.Create);
                StreamWriter swData = new StreamWriter(fsData, Encoding.UTF8);
                swData.NewLine = Environment.NewLine;
                //获取编码
                string bm = Db.Find<SYSTEMKMB>().TELNUM;
                //测区参数
                string sql = @"SELECT CQBH,CQMC FROM SYSTEMCQB
                                    WHERE ZT=1
                                    ORDER BY CQBH";
                foreach (var cq in Db.Query<_CQ>(sql))
                {
                    swData.WriteLine(bm+";" + cq.CQMC + ";KJ440|");
                    swData.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    //综采参数
                    //sql = @"SELECT * FROM ZCSJB_TEMP
	                   //     WHERE CQBH=" + cq.CQBH + " AND ZBH IN (" +
                    //        "SELECT YLFJBH FROM ZCYLFJWZB wz INNER JOIN SYSTEMGZMB gzm ON wz.GZMBH=gzm.GZMBH WHERE CQBH=" + cq.CQBH +
                    //        ") ORDER BY ZBH";
                    IEnumerable<View_ZC_Active> dataZc = null;
                    int count = 0;
                    if (PushZC)
                    {
                        dataZc = Db.QueryWhere<View_ZC_Active>("CQBH="+cq.CQBH);
                        count += dataZc.Count();
                    }
                    //顶板离层参数
                    //sql = @"SELECT * FROM DBLCSJB_TEMP
	                   //     WHERE CQBH=" + cq.CQBH + " AND LCBH IN (" +
                    //        "SELECT CGQBH FROM DBLCCGQWZB wz INNER JOIN SYSTEMXDB xd ON wz.XDBH=xd.XDBH WHERE CQBH=" + cq.CQBH +
                    //        ") ORDER BY LCBH";
                    IEnumerable<View_DBLC_Active> dataDblc = null;
                    if (PushDBLC)
                    {
                        dataDblc = Db.QueryWhere<View_DBLC_Active>("CQBH=" + cq.CQBH);
                        count += dataDblc.Count();
                    }
                    //锚杆/索应力参数
                    //sql = @"SELECT * FROM MGYLSJB_TEMP
	                   //    WHERE CQBH=" + cq.CQBH + " AND MBH IN (" +
                    //        "SELECT CGQBH FROM MGYLCGQWZB wz INNER JOIN SYSTEMXDB xd ON wz.XDBH=xd.XDBH WHERE CQBH=" + cq.CQBH +
                    //        ") ORDER BY MBH";
                    IEnumerable<View_MG_Active> dataMgyl = null;
                    if (PushMGYL)
                    {
                        dataMgyl = Db.QueryWhere<View_MG_Active>("CQBH=" + cq.CQBH);
                        count += dataMgyl.Count();
                    }
                    //测区应力参数CQYLCGQWZB
                    //sql = @"SELECT * FROM CQYLSJB_TEMP
	                   //     WHERE CQBH=" + cq.CQBH + " AND CQYLBH IN (" +
                    //        "SELECT CGQBH FROM MGYLCGQWZB wz INNER JOIN SYSTEMXDB xd ON wz.XDBH=xd.XDBH WHERE CQBH=" + cq.CQBH +
                    //        ") ORDER BY CQYLBH";
                    IEnumerable<View_CQYL_Active> dataCqyl = null;
                    if (PushCQYL)
                    {
                        dataCqyl = Db.QueryWhere<View_CQYL_Active>("CQBH=" + cq.CQBH);
                        count += dataCqyl.Count();
                    }

                    string format = "";
                    bool noBefore = true;
                    //写入文件
                    if (PushZC)
                    {
                        format = "{0:D2}{1:D3}ZP{2};{3:0.0}";
                        for (int i = 0; i < dataZc.Count(); i++)
                        {
                            swData.WriteLine(noBefore ? "|" : "~");
                            noBefore = false;
                            var d = dataZc.ElementAt(i);
                            swData.WriteLine(String.Format(format, cq.CQBH, d.ZBH, 1, d.P1)+"~");
                            swData.WriteLine(String.Format(format, cq.CQBH, d.ZBH, 2, d.P2)+"~");
                            swData.Write(String.Format(format, cq.CQBH, d.ZBH, 3, d.P3));
                        }
                    }
                    if (PushDBLC)
                    {
                        format = "{0:D2}{1:D3}L{2};{3:0.0}";
                        for (int i = 0; i < dataDblc.Count(); i++)
                        {
                            swData.WriteLine(noBefore ? "|" : "~");
                            noBefore = false;
                            var d = dataDblc.ElementAt(i);
                            swData.WriteLine(String.Format(format, cq.CQBH, d.LCBH, 1, d.LCDATAA) + "~");
                            swData.Write(String.Format(format, cq.CQBH, d.LCBH, 2, d.LCDATAB));
                        }
                    }
                    if (PushMGYL)
                    {
                        format = "{0:D2}{1:D3}M;{2:0.0}";
                        for (int i = 0; i < dataMgyl.Count(); i++)
                        {
                            swData.WriteLine(noBefore ? "|" : "~");
                            noBefore = false;
                            var d = dataMgyl.ElementAt(i);
                            swData.Write(String.Format(format, cq.CQBH, d.MBH, d.MDATA));
                        }
                    }
                    if (PushCQYL)
                    {
                        format = "{0:D2}{1:D3}Y;{2:0.0}";
                        for (int i = 0; i < dataCqyl.Count(); i++)
                        {
                            swData.WriteLine(noBefore ? "|" : "~");
                            noBefore = false;
                            var d = dataCqyl.ElementAt(i);
                            swData.Write(String.Format(format, cq.CQBH, d.CQYLBH, d.CQDATA));
                        }
                    }
                    swData.WriteLine("||");
                }
                swData.Flush();
                swData.Close();
                //保存到本地目录
                bool rst = true;
                if (SendLocal)
                {
                    File.Copy("data.txt", SaveDir + "\\" + saveFile);
                    rst &= ftp.Upload(new FileInfo("data.txt"), saveFile);
                }
                if (SendFTP)
                {
                    rst &= ftp.Upload(new FileInfo("data.txt"), saveFile);
                }
                return rst;
            }
            catch (Exception ex)
            {
                lastError = ex.Message;
                LoggerHelper.Error(ex.StackTrace);
                Console.WriteLine(lastError);
            }
            finally
            {
                if (fsData != null)
                {
                    fsData.Close();
                }
            }
            return false;
        }

        /// <summary>
        /// 生成当前时刻系统参数配置文件（新格式）
        /// ftp2
        /// </summary>
        /// <returns>是否成功发送</returns>
        public bool SendIni2(string kjbh,string uploaddir)
        {
            if ((!SendLocal && !SendFTP)
                || (!PushZC && !PushDBLC && !PushMGYL && !PushCQYL))
            {
                return true;
            }
            if (SendFTP && !Connectable(uploaddir))
            {
                return false;
            }
            //生成文件
            FileStream fsDev = null;
            string saveFile = "KYDEV.TXT";// ftp2"+DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + "_config.txt";
            try 
            {
                fsDev = new FileStream("KYDEV.txt", FileMode.Create);
                StreamWriter swDev = new StreamWriter(fsDev, Encoding.UTF8);
                swDev.NewLine = Environment.NewLine;
                //获取编码
                var  bm = Db.Find<SYSTEMKMB>();
                string KMBH=kjbh;//1、煤矿编码；(长度15字符，字符类型)
                string KM = bm.KM;//2、矿井名称
                //测区参数
                string sql = @"SELECT CQBH,CQMC FROM SYSTEMCQB
                                    WHERE ZT=1
                                    ORDER BY CQBH";
                bool noBefore = true;
                foreach (var cq in Db.Query<_CQ>(sql))
                {
                    string HeadTxt = KMBH + "," + KM + "," + cq.CQMC + ",KJ440,";
                    //swDev.WriteLine(KMBH +";"+KM+ ";" + cq.CQMC + ";KJ440|");//4、煤矿监测系统名称
                    //综采参数
                    sql = @"SELECT YLFJBH,GZMMC,WZ,DYZJBH,YLSX,YLXX FROM SYSTEMGZMB gzm
                                INNER JOIN ZCCSB cs on cs.GZMBH=gzm.GZMBH
                                INNER JOIN ZCYLFJWZB wz on wz.GZMBH=gzm.GZMBH
                                WHERE gzm.ZT=1 AND gzm.CQBH=" + cq.CQBH +
                                "ORDER BY gzm.GZMBH,YLFJBH,DYZJBH";
                    IEnumerable<_ZC> iniZc = null;
                    int count = 0;
                    if (PushZC)
                    {
                        iniZc = Db.Query<_ZC>(sql);
                        count += iniZc.Count();
                    }
                    //顶板离层参数
                    sql = @"SELECT CGQBH,XDMC,CGQWZ,WYBJZ FROM SYSTEMXDB xd
                            INNER JOIN DBLCCSB cs on cs.XDBH=xd.XDBH
                            INNER JOIN DBLCCGQWZB wz on wz.XDBH=xd.XDBH
                            WHERE xd.ZT=1 AND xd.CQBH=" + cq.CQBH +
                            "ORDER BY xd.XDBH,CGQBH";
                    IEnumerable<_DBLC> iniDblc = null;
                    if (PushDBLC)
                    {
                        iniDblc = Db.Query<_DBLC>(sql);
                        count += iniDblc.Count();
                    }
                    //锚杆/索应力参数
                    sql = @"SELECT CGQBH,XDMC,CGQWZ,MGBJZ,MSBJZ FROM SYSTEMXDB xd
                            INNER JOIN MGYLCSB cs on cs.XDBH=xd.XDBH
                            INNER JOIN MGYLCGQWZB wz on wz.XDBH=xd.XDBH
                            WHERE xd.ZT=1 AND xd.CQBH=" + cq.CQBH +
                            "ORDER BY xd.XDBH,CGQBH";
                    IEnumerable<_MGYL> iniMgyl = null;
                    if (PushMGYL)
                    {
                        iniMgyl = Db.Query<_MGYL>(sql);
                        count += iniMgyl.Count();
                    }
                    //测区应力参数
                    sql = @"SELECT CGQBH,XDMC,CGQWZ,CQCSYY FROM SYSTEMXDB xd
                            INNER JOIN CQYLCSB cs on cs.XDBH=xd.XDBH
                            INNER JOIN CQYLCGQWZB wz on wz.XDBH=xd.XDBH
                            WHERE xd.ZT=1 AND xd.CQBH=" + cq.CQBH +
                            "ORDER BY xd.XDBH,CGQBH";
                    IEnumerable<_CQYL> iniCqyl = null;
                    if (PushCQYL)
                    {
                        iniCqyl = Db.Query<_CQYL>(sql);
                        count += iniCqyl.Count();
                    }

                    string format = "";
                    
                    //写入文件
                    if (PushZC)
                    {
                        format = HeadTxt+"{0:D2}{1:D3}ZP{2},1,Z,MPa,支架{3}{4},,,,{5}";
                        for (int i = 0; i < iniZc.Count(); i++)
                        {
                            var d = iniZc.ElementAt(i);
                            for (int j = 1; j <= 3; j++)
                            {
                                if (!noBefore) swDev.WriteLine("~");
                                noBefore = false;
                                string line = String.Format(format, cq.CQBH, d.YLFJBH, j, d.DYZJBH, d.WZ, d.GZMMC);
                                swDev.Write(line);
                            }
                        }
                    }
                    if (PushDBLC)
                    {
                        format = HeadTxt+"{0:D2}{1:D3}L{2},2,Z,mm,{3},,,,{4}";
                        for (int i = 0; i < iniDblc.Count(); i++)
                        {
                            var d = iniDblc.ElementAt(i);
                            for (int j = 1; j <= 2; j++)
                            {
                                if (!noBefore) swDev.WriteLine("~");
                                noBefore = false;
                                string line = String.Format(format, cq.CQBH, d.CGQBH, j, d.CGQWZ, d.XDMC);
                                swDev.Write(line);
                            }
                        }
                    }
                    if (PushMGYL)
                    {
                        format = HeadTxt+"{0:D2}{1:D3}M,3,Z,KN,{2},,,,{3}";
                        for (int i = 0; i < iniMgyl.Count(); i++)
                        {
                            if (!noBefore) swDev.WriteLine("~");
                            noBefore = false;
                            var d = iniMgyl.ElementAt(i);
                            string line = String.Format(format, cq.CQBH, d.CGQBH, d.CGQWZ, d.XDMC);
                            swDev.Write(line);
                        }
                    }
                    if (PushCQYL)
                    {
                        format = HeadTxt+"{0:D2}{1:D3}Y,4,Z,KN,,,,,{2}";
                        for (int i = 0; i < iniCqyl.Count(); i++)
                        {
                            if (!noBefore) swDev.WriteLine("~");
                            noBefore = false;
                            var d = iniCqyl.ElementAt(i);
                            string line = String.Format(format, cq.CQBH, d.CGQBH, d.XDMC);
                            swDev.Write(line);
                        }
                    }
                }
                if (!noBefore) swDev.WriteLine("~");
                swDev.Flush();
                swDev.Close();
                //保存到本地目录
                bool rst = true;
                if (SendLocal)
                {
                    //File.Copy("KYDEV.TXT", SaveDir + "\\" + saveFile,true);
                    rst &= ftp.Upload(new FileInfo("KYDEV.TXT"), uploaddir + "\\" + saveFile);
                }
                if (SendFTP)//修改，发送服务器且存本地
                {                   
                    rst &= ftp.Upload(new FileInfo("KYDEV.TXT"),uploaddir+"\\"+ saveFile);
                }
                return rst;
            }
            catch (Exception ex)
            {
                lastError = ex.Message;
                LoggerHelper.Error(ex.StackTrace);
                Console.WriteLine(lastError);
            }
            finally
            {
                if (fsDev != null)
                {
                    fsDev.Close();
                }
            }
            return false;
        }
        /// <summary>
        /// 生成当前时刻数据文件（新格式）
        /// 离当前时刻最近的一次数据
        /// ftp2
        /// </summary>
        /// <returns>是否成功发送</returns>
        public bool SendData2(string kjbh,string uploaddir)
        {
            if ((!SendLocal && !SendFTP)
                || (!PushZC && !PushDBLC && !PushMGYL && !PushCQYL))
            {
                return true;
            }
            if (SendFTP && !Connectable(uploaddir))
            {
                return false;
            }
            //生成文件
            FileStream fsData = null;
            string saveFile = "KYRTDATA.TXT";// "ftp2"+DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + "_data.txt";
            try
            {
                fsData = new FileStream("KYRTDATA.txt", FileMode.Create);
                StreamWriter swData = new StreamWriter(fsData, Encoding.UTF8);
                swData.NewLine = Environment.NewLine;
                //获取编码
                var bm = Db.Find<SYSTEMKMB>();
                string KMBH = kjbh;//1、煤矿编码；(长度15字符，字符类型)
                string KM =  bm.KM;//2、矿井名称

                //测区参数
                string sql = @"SELECT CQBH,CQMC FROM SYSTEMCQB
                                    WHERE ZT=1
                                    ORDER BY CQBH";
                bool noBefore = true;
                DateTime now = DateTime.Now;
                foreach (var cq in Db.Query<_CQ>(sql))
                {
                    string HeadTxt = KMBH + "," + KM + "," ;
                    //swData.Write(KMBH+","+KM + "," + cq.CQMC );//+ cq.CQMC + ","KJ440+ "|\n"
                    //  swData.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "|\n");
                    //综采参数
                    //sql = @"SELECT * FROM ZCSJB_TEMP
                    //     WHERE CQBH=" + cq.CQBH + " AND ZBH IN (" +
                    //        "SELECT YLFJBH FROM ZCYLFJWZB wz INNER JOIN SYSTEMGZMB gzm ON wz.GZMBH=gzm.GZMBH WHERE CQBH=" + cq.CQBH +
                    //        ") ORDER BY ZBH";
                    IEnumerable<View_ZC_Active> dataZc = null;
                    int count = 0;
                    if (PushZC)
                    {
                        dataZc = Db.QueryWhere<View_ZC_Active>("CQBH=" + cq.CQBH);
                        count += dataZc.Count();
                    }
                    //顶板离层参数
                    //sql = @"SELECT * FROM DBLCSJB_TEMP
                    //     WHERE CQBH=" + cq.CQBH + " AND LCBH IN (" +
                    //        "SELECT CGQBH FROM DBLCCGQWZB wz INNER JOIN SYSTEMXDB xd ON wz.XDBH=xd.XDBH WHERE CQBH=" + cq.CQBH +
                    //        ") ORDER BY LCBH";
                    IEnumerable<View_DBLC_Active> dataDblc = null;
                    if (PushDBLC)
                    {
                        dataDblc = Db.QueryWhere<View_DBLC_Active>("CQBH=" + cq.CQBH);
                        count += dataDblc.Count();
                    }
                    //锚杆/索应力参数
                    //sql = @"SELECT * FROM MGYLSJB_TEMP
                    //    WHERE CQBH=" + cq.CQBH + " AND MBH IN (" +
                    //        "SELECT CGQBH FROM MGYLCGQWZB wz INNER JOIN SYSTEMXDB xd ON wz.XDBH=xd.XDBH WHERE CQBH=" + cq.CQBH +
                    //        ") ORDER BY MBH";
                    IEnumerable<View_MG_Active> dataMgyl = null;
                    if (PushMGYL)
                    {
                        dataMgyl = Db.QueryWhere<View_MG_Active>("CQBH=" + cq.CQBH);
                        count += dataMgyl.Count();
                    }
                    //测区应力参数CQYLCGQWZB
                    //sql = @"SELECT * FROM CQYLSJB_TEMP
                    //     WHERE CQBH=" + cq.CQBH + " AND CQYLBH IN (" +
                    //        "SELECT CGQBH FROM MGYLCGQWZB wz INNER JOIN SYSTEMXDB xd ON wz.XDBH=xd.XDBH WHERE CQBH=" + cq.CQBH +
                    //        ") ORDER BY CQYLBH";
                    IEnumerable<View_CQYL_Active> dataCqyl = null;
                    if (PushCQYL)
                    {
                        dataCqyl = Db.QueryWhere<View_CQYL_Active>("CQBH=" + cq.CQBH);
                        count += dataCqyl.Count();
                    }

                    string format = "";
                    //写入文件
                    if (PushZC)
                    {
                        format = "{0:D2}{1:D3}ZP{2},{3:0.0},{4},{5}";
                        for (int i = 0; i < dataZc.Count(); i++)
                        {
                            if (!noBefore) swData.WriteLine("~");
                            noBefore = false;
                            var d = dataZc.ElementAt(i);
                            if (d.ZDATETIME == DateTime.MinValue) d.ZDATETIME = now;
                            swData.WriteLine(String.Format(HeadTxt + format, cq.CQBH, d.ZBH, 1, d.P1, FormateDateForSystemPlat(d.ZDATETIME), d.SFBJ==true?"报警":"正常") + "~");
                            swData.WriteLine(String.Format(HeadTxt + format, cq.CQBH, d.ZBH, 2, d.P2, FormateDateForSystemPlat(d.ZDATETIME), d.SFBJ == true ? "报警" : "正常") + "~");
                            swData.Write(String.Format(HeadTxt + format, cq.CQBH, d.ZBH, 3, d.P3, FormateDateForSystemPlat(d.ZDATETIME), d.SFBJ == true ? "报警" : "正常"));
                        }
                    }
                    if (PushDBLC)
                    {
                        format = "{0:D2}{1:D3}L{2},{3:0.0},{4},{5}";
                        for (int i = 0; i < dataDblc.Count(); i++)
                        {
                            if (!noBefore) swData.WriteLine("~");
                            noBefore = false;
                            var d = dataDblc.ElementAt(i);
                            if (d.LCDATETIME == DateTime.MinValue) d.LCDATETIME = now;
                            swData.WriteLine(String.Format(HeadTxt+format, cq.CQBH, d.LCBH, 1, d.LCDATAA, FormateDateForSystemPlat(d.LCDATETIME), d.SFBJ == true ? "报警" : "正常") + "~");
                            swData.Write(String.Format(HeadTxt+format, cq.CQBH, d.LCBH, 2, d.LCDATAB, FormateDateForSystemPlat(d.LCDATETIME), d.SFBJ == true ? "报警" : "正常"));
                        }
                    }
                    if (PushMGYL)
                    {
                        format = "{0:D2}{1:D3}M,{2:0.0},{3},{4}";
                        for (int i = 0; i < dataMgyl.Count(); i++)
                        {
                            if (!noBefore) swData.WriteLine("~");
                            noBefore = false;
                            var d = dataMgyl.ElementAt(i);
                            if (d.MDATETIME == DateTime.MinValue) d.MDATETIME = now;
                            swData.Write(String.Format(HeadTxt + format, cq.CQBH, d.MBH, d.MDATA, 
                                (d.MDATETIME), d.SFBJ == true ? "报警" : "正常"));
                        }
                    }
                    if (PushCQYL)
                    {
                        format = "{0:D2}{1:D3}Y,{2:0.0},{3},{4}";
                        for (int i = 0; i < dataCqyl.Count(); i++)
                        {
                            if (!noBefore) swData.WriteLine("~");
                            noBefore = false;
                            var d = dataCqyl.ElementAt(i);
                            if (d.CQDATETIME == DateTime.MinValue) d.CQDATETIME = now;
                            swData.Write(String.Format(HeadTxt + format, cq.CQBH, d.CQYLBH, d.CQDATA,  FormateDateForSystemPlat(d.CQDATETIME), ""));

                        }
                    }
                }
                if (!noBefore) swData.WriteLine("~");
                swData.Flush();
                swData.Close();
                //保存到本地目录
                bool rst = true;
                if (SendLocal)
                {
                   // File.Copy("KYRTDATA.TXT", SaveDir + "\\" + saveFile,true);
                    rst &= ftp.Upload(new FileInfo("KYRTDATA.TXT"), uploaddir + "\\" + saveFile);
                }
                if (SendFTP)//修改，上传服务器且存本地
                {
                    rst &= ftp.Upload(new FileInfo("KYRTDATA.TXT"), uploaddir + "\\" + saveFile);
                }
                return rst;
            }
            catch (Exception ex)
            {
                lastError = ex.Message;
                LoggerHelper.Error(ex.StackTrace);
                Console.WriteLine(lastError);
            }
            finally
            {
                if (fsData != null)
                {
                    fsData.Close();
                }
            }
            return false;
        }
        /// <summary>
        /// 根据操作系统进行DateTime格式化
        /// yyyy-MM-dd/hh:mm:ss
        /// </summary>
        /// <returns></returns>

        private string FormateDateForSystemPlat(DateTime dt)
        { 
            if (OSHelper.IsWindows2003 ||
                OSHelper.IsWindows2008 || OSHelper.IsWindows2008R2 ||
                OSHelper.IsWindows2012 || OSHelper.IsWindows2012R2)
            {                
                return dt.ToString("yyyy-MM-dd\\/HH:mm:ss");
            }
            else
                return dt.ToString("yyyy-MM-dd/HH:mm:ss");

        }


        public static void Test()
        {
            FtpService ftpService = new FtpService("127.0.0.1","narvus","sa123");
            ftpService.SendIni();
        }
    }
    /// <summary>
    /// 测区参数配置
    /// </summary>
    class _CQ
    {
        public int CQBH;// 测区编号
        public string CQMC;//测区名称
    }
    /// <summary>
    /// 综采参数配置
    /// </summary>
    class _ZC
    {
        public int CQBH;// 测区编号
        public int YLFJBH;//压力分站编号
        public string KM;//矿名
        public string GZMMC;//工作面名称
        public string WZ;//位置
        public string DYZJBH;//支架编号
        public double YLSX;//压力上限
        public double YLXX;//压力下限
    }
    /// <summary>
    /// 顶板离层参数配置
    /// </summary>
    class _DBLC
    {
        public int CQBH;// 测区编号
        public string CQMC;//测区名称
        public int CGQBH;//传感器编号
        public string KM;//矿名
        public string XDMC;//巷道名称
        public string CGQWZ;//传感器位置
        public int WYBJZ;//位移报警值
    }
    /// <summary>
    /// 锚杆/索应力参数配置
    /// </summary>
    class _MGYL
    {
        public int CQBH;// 测区编号
        public string CQMC;//测区名称
        public int CGQBH;//传感器编号
        public string KM;//矿名
        public string XDMC;//巷道名称
        public string CGQWZ;//传感器位置
        public int MGBJZ;//锚杆报警值
        public int MSBJZ;//锚索报警值
    }

    class _CQYL
    {
        public int CQBH;// 测区编号
        public string CQMC;//测区名称
        public int CGQBH;//传感器编号
        public string KM;//矿名
        public string XDMC;//巷道名称
        public string CGQWZ;//传感器位置
        public double CQCSYY;//初始预压值
    }
}
